package cn.donghuapian.controller;

import cn.donghuapian.component.MinioService;
import cn.donghuapian.entity.ImageEntity;
import cn.donghuapian.service.IImageService;
import cn.donghuapian.vo.ResponseBody;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hzw
 * @since 2024-09-14
 */
@RestController
@RequestMapping("/image")
public class ImageController {

    @Autowired
    private IImageService imageService;

    @Autowired
    private MinioService minioService;

    @PostMapping("/add")
    public ResponseBody add(MultipartFile file) {
//        imageService.add(file, name);
        minioService.uploadFile(file);
        return ResponseBody.success();
    }

    @PostMapping("/update")
    public ResponseBody update(MultipartFile file, String name, int id) {
//        imageService.update(file, name, id);
        return ResponseBody.success();
    }


    @GetMapping("/get/{id}")
    public void get(HttpServletResponse response, @PathVariable int id) throws IOException {
        ImageEntity entity = imageService.getById(id);
        BufferedImage image = null;
        byte[] data = entity.getData();
        OutputStream outputStream = null; 
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        try {
            outputStream = response.getOutputStream();
            image = ImageIO.read(new ByteArrayInputStream(data));
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }
}
